import React from 'react';
import { inject, observer } from 'mobx-react';
import {Icon,message,Modal} from 'antd'
import {WeaBrowser,WeaInput,WeaLocaleProvider,WeaSelect,WeaDatePicker, WeaFormItem, WeaCheckbox, WeaTextarea} from 'ecCom';
import CubeLayout from "../../../../govern/components/E9/cubeLayout";
import * as Util from '../../../util/Util';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
@inject('taskDetailStore')
@observer
export default class BaseInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            urgent: [
                {key: "0",selected: false,showname: getLabel(15808,'未设置')},
                {key: "1",selected: false,showname: getLabel(382501,'重要紧急')},
                {key: "2",selected: false,showname: getLabel(382502,'重要不紧急')},
                {key: "3",selected: false,showname: getLabel(382503,'不重要紧急')},
                {key: "4",selected: false,showname: getLabel(382504,'不重要不紧急')},
            ],
            tododatas: [
                {key: "1",selected: false,showname: getLabel(15537,'今日')},
                {key: "2",selected: false,showname: getLabel(22488,'明天')},
                {key: "3",selected: false,showname: getLabel(382509,'即将')},
                {key: "4",selected: true,showname: getLabel(382499,'不标记')},
                {key: "5",selected: false,showname: getLabel(382498,'备忘')},
            ],
        }
    }
    componentWillMount() {//一些初始化请求
        
    }
    //自定义字段保存
    onCustomChange = (values, type,tablename,fieldmark,labeltype,show_name,logValue,fieldhtmltype) => {
        const { taskDetailStore } = this.props;
        let  {editParams,detailKey} = taskDetailStore;
        if (editParams[type] != values) {
            taskDetailStore.canEdit = false;
            taskDetailStore.editParams[type] = values;
            taskDetailStore.editTaskInfo({
                taskId: detailKey, fieldname: type, fieldvalue: values, fieldmark: fieldmark, labeltype: labeltype,logValue:logValue, 
                showname: show_name,tablename:tablename,iscustom:"1",fieldhtmltype:fieldhtmltype,doback:function(_status,_msg) {
                    if(_status==1){
                        message.success(getLabel(31439,'更新成功'));
                    }else{
                        message.error(_msg);
                    }
                }
            });
        }
    }
    onInputChange = (values, type,tablename,fieldmark,browserShowName) => {//input select textare保存
        const { taskDetailStore } = this.props;
        let  {editParams} = taskDetailStore;
        if (editParams[type] != values) {
            taskDetailStore.canEdit = false;
            if(type=="name" && (values.trim()=="" || values.trim()=="null")){
                message.warning(getLabel(504646,'任务名称不能为空'));
                taskDetailStore.canEdit = true;
                return;
            }
            if(type=="principalid"){
                if(values==""){
                    message.warning(getLabel(508793,'责任人不能为空!'));
                    taskDetailStore.canEdit = true;
                    return;
                }
                taskDetailStore.editParams["principalArray"] = [{id:values,name:browserShowName}];
            }
            if(type=="begindate" && editParams['enddate']!=""){
                if(Util.DateDiffDays(values,editParams['enddate'])<0){
                    message.warning(getLabel(16721,'开始日期不能大于结束日期'));
                    if(fieldmark!=undefined && fieldmark!=""){
                        window.ModeForm.changeFieldValue(fieldmark, {
                            value: editParams['begindate'],   
                            showhtml: editParams['begindate'] 
                        }); 
                    }
                    taskDetailStore.canEdit = true;
                    return;
                }
            }
            if(type=="enddate" && editParams['begindate']!=""){
                if(Util.DateDiffDays(values,editParams['begindate'])>0){
                    message.warning(getLabel(83347,'结束日期不能小于开始日期'));
                    if(fieldmark!=undefined && fieldmark!=""){
                        window.ModeForm.changeFieldValue(fieldmark, {
                            value: editParams['enddate'],   
                            showhtml: editParams['enddate'] 
                        }); 
                    }
                    taskDetailStore.canEdit = true;
                    return;
                }
            }
            taskDetailStore.editParams[type] = values;
            this.editTaskInfo(type, values, 'str','','',tablename);
        }
    }
     /**
   * 即时保存页面修改的值（浏览）
   */
  onChangeBrowser = (ids, names, datas, typeIds, typeArray,_isMandatory) => {
    const { taskDetailStore } = this.props;
    if (ids.length > 0) {
        let sendValue = '';
        let newAddValues = '';
        let delValues = "";
        let idsArray = ids.split(',');
        let canSave = false;
        //taskDetailStore.canEdit = false;
        //替换数组
        if (typeIds == 'partnerid' || typeIds == 'sharerid' || typeIds == 'tag') {
            newAddValues = Util.ArrayDiffer(taskDetailStore.editParams[typeIds],idsArray,2);
            if(!Util.startWith(ids, ',')){
                ids = ","+ids;
            }
            if(!Util.endWith(ids, ',')){
                ids = ids+",";
            }
            delValues =  Util.ArrayDiffer(taskDetailStore.editParams[typeIds],ids,1);
        }
        if(typeIds == 'principalid' || typeIds == 'parentid'){//责任人和上级任务
            taskDetailStore.editParams[typeIds] = ids;
            taskDetailStore.editParams[typeArray] = datas;
            sendValue = ids;
            canSave = true;
        }else{
            if(newAddValues!="" || delValues!=""){
                taskDetailStore.editParams[typeIds] = ids;
                taskDetailStore.editParams[typeArray] = datas;
                sendValue = ids;
                canSave = true;
            }
        }
        if (canSave) {
            this.editTaskInfo(typeIds, sendValue, 'str', newAddValues,delValues);
        } 
      }else{
        if (typeIds == 'partnerid' || typeIds == 'sharerid' || typeIds == 'tag' || typeIds == 'parentid') {
            if(_isMandatory){
                message.warning(getLabel(386866, '此项不能为空'));
                return;
            }
            let delvalue = taskDetailStore.editParams[typeIds];
            taskDetailStore.editParams[typeIds] = "";
            taskDetailStore.editParams[typeArray] = [];
            this.editTaskInfo(typeIds, "", 'str', "",delvalue);
        }else if(typeIds == 'principalid'){
            taskDetailStore.editParams[typeArray] = [];
            Modal.warning({
                title: getLabel(558,'提示'),
                content: getLabel(508793,'责任人不能为空!'),
            });
        }
      }
    }
   
    /**参数同步修改数据 type修改字段 values修改的值 newAddValues新增的值 delValues 删除的值*/
    editTaskInfo(type, values, fieldtype, newAddValues, delValues,tablename) {
        const { taskDetailStore } = this.props;
        const{detailKey} = taskDetailStore;
        let _this = this;
        taskDetailStore.canEdit = false;
        taskDetailStore.editTaskInfo({
            taskId: detailKey, fieldname: type, fieldvalue: values, fieldtype: fieldtype, addvalue: newAddValues, delvalue: delValues,tablename:tablename, doback:function() {
                _this.doCallBack(type);
                message.success(getLabel(31439,'更新成功'));
            }
        });
    }
    //编辑修改内容回调taskMain.js
    doCallBack(type,dataArray,key,cstatus) {
        if (typeof this.props.doCallBack === "function") {
            this.props.doCallBack(type,dataArray,key,cstatus);
        }
    }
    //相关信息点击和删除
    onLinkClick(id, name, type,typeIds, typeArray,fileid){
        const { taskDetailStore } = this.props;
        if(type==2){
            taskDetailStore.canEdit = false;
            //对IDS进行处理
            let vals = taskDetailStore.editParams[typeIds];
            if (vals.length > 0 && !Util.startWith(vals, ',')) {
                vals = ',' + vals;
            }
            if (vals.length > 0 && !Util.endWith(vals, ',')) {
                vals = vals + ',';
            }
            let sendValue = '';
            let fieldtype = '';
            let _index = vals.indexOf("," + id + ",");
            if (_index > -1 && id != "") {
                vals = vals.substring(0, _index + 1) + vals.substring(_index + (id + "").length + 2);
                if (vals == ',') {
                    vals = '';
                }
                taskDetailStore.editParams[typeIds] = vals;
                if (typeIds == 'fileids') {//附件
                    sendValue = id;
                    fieldtype = 'del';
                }else { //其他
                    sendValue = vals;
                    fieldtype = 'str';
                }
            }
            //对array进行处理
            let array = taskDetailStore.editParams[typeArray];
            array.map((elemnet, index) => {
                if (elemnet.id == id) {
                    taskDetailStore.editParams[typeArray].remove(elemnet);
                }
            });
            this.editTaskInfo(typeIds, sendValue, fieldtype, '', id);
        }
    }
    //建模特殊字段处理
    getEcmeFieldData = (path, param) => {
        const {taskDetailStore:{cubeLayoutParame,editParams,canShow,canEdit,detailKey,onNodeClick} } = this.props;
        const { specialFields } = cubeLayoutParame;
        const {tododatas} = this.state;
        if (_.has(specialFields, path)) {
            let _isMandatory = param.isMandatory;
            // if (specialFields[path].fieldname == 'tag') {
            //     return <WeaBrowser onChange={(ids, names, datas) => { this.onChangeBrowser(ids, names, datas,"tag","tagArray",_isMandatory) }}
            //     type="wrltag" inputStyle={{ width: 245 }} isSingle={false} viewAttr={_isMandatory?3:canShow ? '2' : '1'} title={getLabel(30878,'任务标签')}
            //     replaceDatas={toJS(editParams.tagArray)}
            //     />
            // }
            let fieldname = specialFields[path].fieldname
            let fieldright = this.getColumnFieldRight(fieldname)
            if(fieldname == 'showallsub'){
                return fieldright != "0" && <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@y519vj`} value={editParams.showallsub} viewAttr={fieldright || (_isMandatory?3:canShow ? '2' : '1')} display="switch" id="showallsub" style={{ display: 'inline' }} onChange={(v) => this.onInputChange(v, "showallsub")} />
            }
            if(fieldname == 'todoval' && fieldright != "0"){
                return <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@s87l5c`} options={tododatas} viewAttr={fieldright || (_isMandatory?3:2)} value={editParams.todotype} onChange={(key) => this.onInputChange(key,"todotype")} />
            }
            if(fieldname == 'parentid'){
                return fieldright != "0" && <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@qewidx`} title={getLabel(23785,'上级任务')}
                onChange={(ids, names, datas) => { this.onChangeBrowser(ids, names, datas, "parentid","parentArray",_isMandatory) }}
                replaceDatas={toJS(editParams.parentArray)} icon ="icon-coms-implement"
                iconBgcolor="rgb(150, 53, 138)"
                type="wrltsk" hasAdvanceSerach={true} viewAttr={fieldright || (_isMandatory?3:canShow?2:1)} inputStyle={{ width: 245 }}
                onLinkClick = {(e,item)=>{onNodeClick({key:item.id})}}
                dataParams ={{parentid:detailKey}}
                completeParams = {{parentid:detailKey}}/>
            }
            if(fieldname == 'partnerid' || fieldname == 'sharerid'){
                let _title = getLabel(382557,'参与人');
                let _carray = "partnerArray";
                if(fieldname == 'sharerid'){
                    _title = getLabel(382597,'分享人');
                    _carray = "sharerArray";
                }
                return fieldright != "0" && <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@w2nce3`} title={_title}
                onChange={(ids, names, datas) => { this.onChangeBrowser(ids, names, datas, fieldname,_carray,_isMandatory) }}
                replaceDatas={toJS(editParams[_carray])}  isSingle={false}
                type="17" viewAttr={fieldright || (_isMandatory?3:canShow?2:1)} inputStyle={{ width: 245 }}/>
            }
        }
        return null;
    }
    ecmeCallBack =()=>{
        const {taskDetailStore } = this.props;
        taskDetailStore.spinning = false;

        let fields = taskDetailStore.Card.allFields
        for(let key in fields){
            let fieldname = fields[key].fieldname
            let fieldright = this.getColumnFieldRight(fieldname)
            if (fieldright == "0") {
                fieldright = "4"   // '4'为隐藏项，'5'为隐藏行
            }
            fieldright && window.ModeForm.changeFieldAttr(key, fieldright)
        }
    }
    getColumnFieldRight = (fieldname) => {
        const { columnFieldRightMap, canShow } = this.props.taskDetailStore
        let fieldright = columnFieldRightMap[fieldname] || ""
        if (!canShow && fieldname != "todotype" && fieldname != "todoval" && fieldright && parseInt(fieldright) > 1) {
            fieldright = "1"
        }
        return fieldright
    }
    //type-onChange onblur onfoncus fieldname-更改的字段 tablename-更改的表名 fieldhtmltype-更改字段类型 newvalue-更改后的值 rowIndex-明细表主键id
    ecmeFieldEventCallBack=(datas)=>{
        let type =  datas.changetype;
        let fieldInfo = datas.fieldInfo;
        let fieldname = fieldInfo.fieldname;
        let fieldhtmltype = fieldInfo.fieldhtmltype;
        let tablename = fieldInfo.tablename;
        let newvalue =  datas.fieldnewvalue;
        let fieldmark = datas.fieldMark;
        let iscustom = datas.iscustom;
        let rowIndex = datas.rowIndex;
        let isCallBack = false;
        if(ModeForm.getFieldCurViewAttr(fieldmark) == 3 && Util.isEmpty(newvalue) && type != "onfocus"){
            //ModeForm.changeFieldValue(fieldmark,{value:oldvalue})
            message.warning(getLabel(509065, '请输入必填项'));
            return;
        }
        if(fieldhtmltype==1 || fieldhtmltype==2){
           if(type=="onblur"){
            isCallBack = true;
           }
        }else if(type=="onChange"){
            isCallBack = true;
        }
        if(isCallBack){
            if(iscustom=="true"){
                let logValue = newvalue;
                if(fieldhtmltype==3){//浏览按钮
                    logValue = datas.browserShowName;
                }
                if(fieldhtmltype==4){//复选框
                    logValue = newvalue==0?"No":"Yes";
                }
                if(fieldhtmltype==5){//下拉框
                    logValue = this.getCustomeSelectName(newvalue,fieldInfo.options);
                }
                let labeltype = fieldInfo.labeltype;
                let show_name = fieldInfo.fieldlabelid;
                if(labeltype==1){
                    show_name = fieldInfo.showname;
                }
                this.onCustomChange(newvalue,fieldname,tablename,fieldmark,labeltype,show_name,logValue,fieldhtmltype);
            }else{
                this.onInputChange(newvalue,fieldname,tablename,fieldmark,datas.browserShowName);
            }
        }
    }
    //自定义字段下拉选择框得到showname
    getCustomeSelectName(val,datas){
        let showname = val;
        datas && datas.length>0 && datas.map((element,idx)=>{
            if(element.key==val){
                showname = element.showname;
            }
        })
        return showname;
    }
    render() {
        const { taskDetailStore } = this.props;
        const { editParams, canEdit,canShow, hasData,columnList,detailKey,onNodeClick} = taskDetailStore;
        let{cubeLayoutParame,getCardStorefun} = taskDetailStore;
        let cubeFlag = Object.keys(toJS(cubeLayoutParame)).length > 0;
        return (
            <div className="wea-search-group">
                {hasData && 
                      <div className="wea-workrelate-taskedit-basecontent">
                      {cubeFlag? (CubeLayout({ cubeLayoutParame, "getEcmeFieldData": this.getEcmeFieldData,"callback":this.ecmeCallBack,"ecmeFieldEventCallBack":this.ecmeFieldEventCallBack, getCardStorefun })) :
                           columnList && columnList.length>0 && columnList.map((element,idx)=>{
                                let fieldright = this.getColumnFieldRight(element.columninfo)
                                return ( fieldright != "0" &&
                                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2x9vck@${element.columninfo}`} label={getLabel(element.languageid,element.name)} labelCol={{span: 6}} wrapperCol={{span: 18}}> 
                                     {element.type==1 && 
                                         <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@6akoe9@${element.columninfo}`} 
                                             viewAttr={ fieldright || (canShow ?element.columninfo=="name"?'3':"2" : '1')} 
                                             value={editParams[element.columninfo]} 
                                             onBlur={(value) => this.onInputChange(value,element.columninfo)}
                                         />
                                     }

                                     {element.type==2 && 
                                         <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@9fe98g@${element.columninfo}`} 
                                             onChange={(ids, names, datas) => { this.onChangeBrowser(ids, names, datas, element.columninfo, element.columnarray) }}
                                             replaceDatas={toJS(editParams[element.columnarray])} 
                                             title={getLabel(element.languageid,element.name)} 
                                             type={element.browstype}
                                             inputStyle={{ width: 242 }} 
                                             isSingle ={element.browssingle}
                                             hasAdvanceSerach={true}
                                             viewAttr={fieldright || (canShow ?(element.columninfo=="principalid"?"3":"2") : '1')}
                                             linkUrl={element.browslinkurl?element.browslinkurl:""}
                                             icon ={element.columninfo=="parentid"?"icon-coms-implement":"icon-toolbar-Organization-list"}
                                             iconBgcolor={element.columninfo=="parentid"?"rgb(150, 53, 138)":"rgb(74, 144, 226)"}
                                             onLinkClick = {element.columninfo=="parentid"?(e,item)=>{onNodeClick({key:item.id})}:""}
                                             dataParams ={element.columninfo=="parentid"?{parentid:detailKey}:""}
                                             completeParams = {element.columninfo=="parentid"?{parentid:detailKey}:""}
                                         />
                                     }

                                     {element.type==3 && 
                                         <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@wgvgpn@${element.columninfo}`} 
                                             options={this.state[element.columnarray]}   
                                             viewAttr={fieldright || ((canShow || (element.columninfo=="todotype" && editParams.status=="1")) ? '2' : '1')} 
                                             value={editParams[element.columninfo]} 
                                             onChange={(key) => this.onInputChange(key,element.columninfo)} 
                                         />
                                     }

                                     {element.type==4 && 
                                         <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@kffyh7@${element.columninfo}`} 
                                             value={editParams[element.columninfo]}  
                                             viewAttr={fieldright || (canShow ? '2' : '1')} 
                                             onChange={value => this.onInputChange(value,element.columninfo)} 
                                             style={{width:242}}
                                         /> 
                                     }

                                     {element.type==5 && 
                                         <WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@njjzw3@${element.columninfo}`} 
                                             value={editParams[element.columninfo]}  
                                             viewAttr={fieldright || (canShow ? '2' : '1')} 
                                             onBlur={value => this.onInputChange(value, element.columninfo)} 
                                         /> 
                                     }

                                     {element.type==7 && 
                                         <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@xb9qnh@${element.columninfo}`} 
                                             value={editParams[element.columninfo]}  
                                             viewAttr={fieldright || (canShow ? '2' : '1')} 
                                             // disabled={!canShow} 
                                             display="switch" 
                                             id={element.columninfo} 
                                             style={{ display: 'inline' }} 
                                             onChange={(v) => this.onInputChange(v, element.columninfo)} 
                                         />
                                     }
                                    </WeaFormItem>
                                )
                           })}
                        </div>}
            </div >
        )
    }
};